package com.ruoyi.web.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eic.common.util.LambdaUtils;
import com.ruoyi.common.annotation.HasPermi;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.dao.SysPost;
import com.ruoyi.system.domain.dao.SysRole;
import com.ruoyi.system.domain.dao.SysUser;
import com.ruoyi.system.domain.dao.SysUserPasswd;
import com.ruoyi.system.domain.persist.SysUserPo;
import com.ruoyi.system.domain.query.SysUserQo;
import com.ruoyi.system.domain.view.SysRoleVo;
import com.ruoyi.system.domain.view.SysUserVo;
import com.ruoyi.system.domain.wrapper.query.SysUserWrapperQ;
import com.ruoyi.system.domain.wrapper.view.SysUserWrapperV;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
/**
 * 用户信息Controller
 *
 * @author 尹国春
 * @date 2022-07-20
 */
@Api(value = "用户信息", tags = {"用户信息"})
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 用户信息分页查询
     */
    @ApiOperation(value="用户信息分页查询",notes="分页参数：pageNum,pageSize,orderByColumn(数据库字段名称),isAsc(asc|desc)")
    @HasPermi("system:user:list")
    @GetMapping("/list")
    public TableDataInfo<SysUserVo> list(SysUserQo sysUser)
    {
        IPage<SysUser> page=userService.page(sysUser.getPage(), SysUserWrapperQ.getQueryWrapper(sysUser));
        return SysUserWrapperV.build().pageVO(page);
    }

    /**
     * 用户信息导出
     */
    @ApiOperation("用户信息导出")
    @HasPermi("system:user:list")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUserQo sysUser)
    {
        List<SysUser> list = userService.list(SysUserWrapperQ.getQueryWrapper(sysUser));
        List<SysUserVo> voList = SysUserWrapperV.build().listVO(list);
        ExcelUtil<SysUserVo> util = new ExcelUtil<>(SysUserVo.class);
        util.exportExcel(response, voList, "用户信息数据");
    }


    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @HasPermi("system:user:edit")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @HasPermi("system:user:list")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId)
    {
        Map<String,Object> data = new HashMap<>();
        List<SysRole> roles = roleService.list(null);
        data.put("roles", roles);
        data.put("posts", postService.list(null));
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.getById(userId);
            data.put("user", SysUserWrapperV.build().entityVO(sysUser));
            data.put("postIds", LambdaUtils.listFieldValue(postService.selectPostListByUserId(userId), SysPost::getPostId));
            data.put("roleIds", sysUserRoleMapper.selectRoleIds(userId));
        }
        return AjaxResult.success(data);
    }

    /**
     * 新增用户
     */
    @HasPermi("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUserPo user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @HasPermi("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUserPo user)
    {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @HasPermi("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable String[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.removeByIds(Arrays.asList(userIds)));
    }

    /**
     * 重置密码
     */
    @HasPermi("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUserPasswd user)
    {
        return toAjax(userService.resetPasswd(user));
    }

    /**
     * 状态修改
     */
    @HasPermi("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        return toAjax(userService.updateById(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @HasPermi("system:user:list")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") String userId)
    {
        Map<String,Object> data = new HashMap<>();
        SysUser user = userService.getById(userId);
        List<SysRoleVo> roles = roleService.selectRolesByUserId(userId);
        data.put("user", user);
        data.put("roles", SecurityUtils.isAdmin(userId) ? roles : roles.stream().collect(Collectors.toList()));
        return AjaxResult.success(data);
    }

    /**
     * 用户授权角色
     */
    @HasPermi("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(String userId, String[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }
}
